﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;

using IBatisNet.DataAccess;

using AUV5.Model;
using AUV5.DAL;
using AUV5.DAL.Interface;
using AUV5.DAL.Dao;
using IBatisNet.DataAccess.Interfaces;
using System.IO;
using AUV5.Common;


namespace AUV5.BLL
{
    /// <summary>
    /// 功能：     ServiceInfo业务逻辑实现
    /// 作者：     lwl
    /// 日期：     2011/10/14
    /// 修改日期： 
    /// 修改人：
    /// 修改内容：
    /// </summary>
    public class ServiceInfoBLL : BaseBLL
    {
        private static ServiceInfoBLL instance = null;
        private static object syncRoot = new object();
        private IDaoManager daoManager = ServiceConfig.Instance.DaoManager;
        private IServiceInfoDao dao = null;

        private ServiceInfoBLL()
        {
            dao = ServiceInfoSqlMapDao.Instance;
        }

        public static ServiceInfoBLL Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new ServiceInfoBLL();
                        }
                    }
                }
                return instance;
            }
        }

        #region 基本操作
        /// <summary>
        /// 得到最大行数
        /// </summary>
        /// <returns></returns>
        public int GetMaxCounts()
        {
            try
            {
                //daoManager.BeginTransaction();

                int count = dao.GetMaxCounts();

                //daoManager.CommitTransaction();

                return count;
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 得到列表
        /// </summary>
        /// <returns></returns>
        public System.Collections.Generic.IList<ServiceInfo> GetList()
        {
            try
            {
                //daoManager.BeginTransaction();

                System.Collections.Generic.IList<ServiceInfo> list = dao.GetList();

                //daoManager.CommitTransaction();

                return list;
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 通过不同参数得到列表
        /// </summary>
        /// <param name="TopCounts"></param>
        /// <returns></returns>
        private System.Collections.Generic.IList<ServiceInfo> GetListByParameters(object TopCounts, ServiceInfo serviceinfo)
        {
            try
            {
                //daoManager.BeginTransaction();

                Hashtable ht = new Hashtable();
                ht.Add("TopCounts", TopCounts);
                System.Collections.Generic.IList<ServiceInfo> list = dao.GetListByParameters(ht);

                //daoManager.CommitTransaction();

                return list;
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 通过服务状态参数得到某用户的服务列表
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="status"></param>
        /// <param name="isEqual">true为等于，false为大于等于</param>
        /// <returns></returns>
        public System.Collections.Generic.IList<ServiceInfo> GetListByStatus(string UserId, Common.Enum.ServiceStatus status, bool isEqual)
        {
            try
            {
                //daoManager.BeginTransaction();

                Hashtable ht = new Hashtable();
                ht.Add("UserID", UserId);

                //是等于该状态还是大于等于该状态
                if (isEqual)
                    ht.Add("StatusID", Convert.ToInt16(status));
                else
                    ht.Add("StatusIDGreatthanOrEqual", Convert.ToInt16(status));

                ht.Add("State", Convert.ToInt32(AUV5.Common.Enum.auvState.Enabled));
                ht.Add("IsDel", Convert.ToInt32(AUV5.Common.Enum.auvDel.NotDel));

                //daoManager.CommitTransaction();

                return dao.GetListByStatus(ht); ;
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 通过服务状态参数得到某用户的服务列表，等于
        /// by amos
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public System.Collections.Generic.IList<ServiceInfo> GetListByStatus(string UserId, Common.Enum.ServiceStatus status)
        {
            try
            {
                return this.GetListByStatus(UserId, status, true);
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 得到明细
        /// </summary>
        /// <param name="ServiceID"></param>
        /// <returns></returns>
        public ServiceInfo GetDetail(System.String serviceid)
        {
            try
            {
                ///daoManager.BeginTransaction();
                Hashtable ht = new Hashtable();
                ht.Add("ServiceID", serviceid ?? "");
                return dao.GetDetail(ht);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 修改信息
        /// </summary>
        /// <param name="service"></param>
        public void Update(ServiceInfo service)
        {
            try
            {
                dao.Update(service);
            }
            catch
            {

                throw;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ServiceID"></param>
        /// <returns></returns>
        public int Delete(System.String serviceid)
        {
            try
            {
                ///daoManager.BeginTransaction();

                return dao.Delete(serviceid);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="serviceinfo"></param>
        /// <returns></returns>
        public int Delete(ServiceInfo serviceinfo)
        {
            try
            {
                ///daoManager.BeginTransaction();

                return dao.Delete(serviceinfo);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }
        #endregion

        #region 通过标题获取服务
        /// <summary>
        /// 通过标题获取服务
        /// </summary>
        public ServiceInfo GetDetailByTitle(string title)
        {
            try
            {
                Hashtable ht = new Hashtable();
                ht.Add("Title", title);
                return dao.GetDetail(ht);
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region 添加服务

        public void AddService(
            string userID,
            string price,
            string title,
            string categoryID,
            string description,
            string duration,
            bool shippable,
            string shipcharge,
            string serviceFrom,
            bool isTimeLimited,
            string lengthOfTime,
            bool isQtyLimited,
            string stock,
            string[] keywords,
            List<string> imglist,
            ref Hashtable errors
            )
        {

            #region 数据验证

            //标题
            if (string.IsNullOrEmpty(title))
            {
                errors.Add(111, "标题不能为空！");
            }
            else if (BadWordsFilter.Instance.HasBadWord(title))
            {
                errors.Add(112, "标题中含有敏感字！");
            }
            else if (BLL.ServiceInfoBLL.instance.TitleExists(title, ""))
            {
                errors.Add(113, "标题已存在！");
            }

            //类别
            if (string.IsNullOrEmpty(categoryID))
            {
                errors.Add(114, "标题类别不能为空！");
            }

            //描述
            if (BadWordsFilter.Instance.HasBadWord(description))
            {
                errors.Add(115, "描述中含有敏感字！");
            }
            //关键字
            foreach (string key in keywords)
            {
                if (key.Length > 10 || key.Length == 0)
                {
                    errors.Add(116, "关键字长度必须大于0小于10！");
                }

            }
            if (imglist.Count == 0)
            {
                errors.Add(117, "至少上传一张图片！");
            }

            //价格
            decimal servicePrice = 0;
            try
            {
                servicePrice = decimal.Parse(price);
            }
            catch (Exception)
            {
                errors.Add(118, "服务价格必须为合法数字！");
            }

            //完成所需时间
            int serviceDuration = 0;
            try
            {
                serviceDuration = int.Parse(duration);
            }
            catch (Exception)
            {
                errors.Add(119, "服务完成所需时间必须为整数！");
            }

            //运费
            decimal serviceShipCharge = 0;
            try
            {
                serviceShipCharge = decimal.Parse(shipcharge);
            }
            catch (Exception)
            {
                errors.Add(120, "运费必须为合法数字");
            }

            //有效期
            int serviceLengthOfTime = 0;
            try
            {
                serviceLengthOfTime = int.Parse(lengthOfTime);
            }
            catch (Exception)
            {
                errors.Add(121, "有效期必须为整数");
            }

            //库存
            int serviceStock = 0;
            try
            {
                serviceStock = int.Parse(stock);
            }
            catch (Exception)
            {
                errors.Add(122, "库存必须为整数");
            }
            #endregion
            if (errors.Count == 0)
            {
                Model.ServiceInfo service = new Model.ServiceInfo();

                //赋值
                service.UserID = userID;
                service.Price = servicePrice;
                service.Title = title;
                service.CategoryID = categoryID;
                service.Description = description;
                service.Instruction = "";
                service.Duration = int.Parse(duration);
                service.Shippable = shippable;
                service.NativeShipCharge = shippable ? serviceShipCharge : 0;
                service.OtherShipCharge = service.NativeShipCharge;
                //暂时存储的是IP地址
                service.ServiceFrom = serviceFrom;

                //限时
                if (isTimeLimited)
                {
                    service.EndDate = DateTime.Now.AddDays(serviceLengthOfTime);
                }
                else
                {
                    service.EndDate = DateTime.MaxValue;
                }

                service.NeedStock = isQtyLimited;

                //限量
                if (isQtyLimited)
                {
                    service.Stock = serviceStock;
                }
                else
                {
                    service.NeedStock = false;
                    service.Stock = 0;
                }
                service.ExtraFor = "";

                //添加服务 
                service.ServiceID = Guid.NewGuid().ToString();

                Add(service, keywords, imglist);
            }
        }

        /// <summary>
        /// 添加服务信息
        /// </summary>
        /// <param name="serviceinfo"></param>
        /// <returns></returns>
        public void Add(ServiceInfo serviceinfo, string[] keywords, List<string> imglist)
        {
            try
            {
                #region //HTML代码处理

                serviceinfo.Title = serviceinfo.Title.HTMLEnCode();
                serviceinfo.Description = serviceinfo.Description.HTMLEnCode();
                serviceinfo.Instruction = serviceinfo.Instruction.HTMLEnCode();
                for (int i = 0; i < keywords.Length; i++)
                {
                    keywords[i] = keywords[i].HTMLEnCode();
                }
                #endregion

                //关键字处理，去重复
                ArrayList keylist = new ArrayList();
                foreach (var key in keywords)
                {
                    if (!keylist.Contains(key) && !string.IsNullOrEmpty(key))
                    {
                        keylist.Add(key);
                    }
                }

                //先进行图片处理
                for (int i = 0; i < imglist.Count; i++)
                {
                    imglist[i] = ImageProcess(imglist[i]);
                }

                daoManager.BeginTransaction();
                //添加服务
                serviceinfo.StatusID = (int)Common.Enum.ServiceStatus.Active;
                serviceinfo.State = (int)Common.Enum.auvState.Enabled;
                serviceinfo.IsDel = (int)Common.Enum.auvDel.NotDel;
                serviceinfo.CreateDate = DateTime.Now;
                serviceinfo.UpdateDate = DateTime.Now;
                dao.Add(serviceinfo);
                //添加关键字及关联
                foreach (var key in keylist)
                {
                    Keyword keyword = new Keyword();
                    keyword.Content = key.ToString().ToLower();

                    //判断关键字不存在则添加到数据库中，存在则返回该KeyID
                    string keyid = KeywordBLL.Instance.AddKey(keyword);

                    ServiceKeyRela rela = new ServiceKeyRela();
                    rela.RelaID = Guid.NewGuid().ToString();
                    rela.ServiceID = serviceinfo.ServiceID;
                    rela.KeyID = keyid;
                    ServiceKeyRelaBLL.Instance.Add(rela);
                }

                //添加图片
                foreach (var path in imglist)
                {
                    ServiceAttachment att = new ServiceAttachment();
                    att.ServiceID = serviceinfo.ServiceID;
                    att.ImagePath = path;
                    att.VideoPath = "";
                    att.VideoLength = "";
                    att.State = (int)Common.Enum.auvState.Enabled;
                    att.IsDel = (int)Common.Enum.auvDel.NotDel;

                    att.CreateDate = DateTime.Now;
                    att.UpdateDate = DateTime.Now;
                    att.BeginDate = DateTime.Now;
                    att.EndDate = DateTime.Now; ;

                    ServiceAttachmentBLL.Instance.Add(att);
                }

                daoManager.CommitTransaction();
            }
            catch
            {
                daoManager.RollBackTransaction();
                throw;
            }
        }
        #endregion

        #region 修改服务
        /// <summary>
        /// 修改信息，包括关键字和图片
        /// </summary>
        /// <param name="serviceinfo"></param>
        /// <returns></returns>
        public void Update(ServiceInfo serviceinfo, string[] keywords, List<string> imglist)
        {
            try
            {
                #region //HTML代码处理

                serviceinfo.Title = serviceinfo.Title.HTMLEnCode();
                serviceinfo.Description = serviceinfo.Description.HTMLEnCode();
                serviceinfo.Instruction = serviceinfo.Instruction.HTMLEnCode();
                for (int i = 0; i < keywords.Length; i++)
                {
                    keywords[i] = keywords[i].HTMLEnCode();
                }
                #endregion

                //关键字处理，去重复
                ArrayList keylist = new ArrayList();
                foreach (var key in keywords)
                {
                    if (!keylist.Contains(key) && !string.IsNullOrEmpty(key))
                    {
                        keylist.Add(key);
                    }
                }

                //先进行图片处理
                IList<Model.ServiceAttachment> attlist = GetAttachWithoutVideo(serviceinfo.ServiceID);
                string[] tempimg = imglist.ToArray();
                Model.ServiceAttachment[] tempatt = ((List<Model.ServiceAttachment>)attlist).ToArray();
                for (int i = 0; i < tempimg.Length; i++)
                {
                    for (int j = 0; j < tempatt.Length; j++)
                    {
                        //重复数据不需要重新处理
                        if (tempatt[j].ImagePath == tempimg[i])
                        {
                            imglist.Remove(tempimg[i]);
                            attlist.Remove(tempatt[j]);
                        }
                    }
                }
                //添加新图
                for (int i = 0; i < imglist.Count; i++)
                {
                    imglist[i] = ImageProcess(imglist[i]);
                }
                //移除旧图
                ServiceAttachmentBLL.Instance.RemoveAttachment(attlist);

                daoManager.BeginTransaction();
                //更新数据
                dao.Update(serviceinfo);

                //先禁用该服务的所有关键字关系
                Hashtable ht = new Hashtable();
                ht.Add("serviceID", serviceinfo.ServiceID);
                ht.Add("state", (int)Common.Enum.auvState.Enabled);
                ////不限制State，但实际上只对State=1的数据起作用
                IList<ServiceKeyRela> list = ServiceKeyRelaSqlMapDao.Instance.GetListByParameters(ht);
                //如果在list.count=0的情况下执行批量修改，则会因为失去条件而将所有数据都改掉
                if (list.Count > 0)
                {
                    ht.Clear();
                    ht.Add("list", list);
                    BLL.ServiceKeyRelaBLL.Instance.DisableList(ht);
                }
                foreach (var key in keylist)
                {
                    //添加关键字
                    Keyword keyword = new Keyword();
                    keyword.Content = key.ToString();

                    string keyid = BLL.KeywordBLL.Instance.AddKey(keyword);
                    //添加或更新关联
                    //查看是否已存在关联
                    ht.Clear();
                    ht.Add("serviceID", serviceinfo.ServiceID);
                    ht.Add("keyID", keyid);
                    ht.Add("state", Common.Enum.auvState.Disable);
                    ServiceKeyRela rela = new ServiceKeyRela();
                    //不限制State，但实际上查出来的都是State=0值
                    list = ServiceKeyRelaSqlMapDao.Instance.GetListByParameters(ht);
                    if (list.Count > 0)
                    {
                        rela = list[0];
                        rela.State = 1;
                        ServiceKeyRelaBLL.Instance.Update(rela);
                    }
                    else
                    {
                        rela.RelaID = Guid.NewGuid().ToString();
                        rela.ServiceID = serviceinfo.ServiceID;
                        rela.KeyID = keyid;
                        ServiceKeyRelaBLL.Instance.Add(rela);
                    }
                }

                //更新附件
                foreach (var path in imglist)
                {
                    //或者可以在此处判断文件是否存在
                    if (path != "")
                    {
                        ServiceAttachment att = new ServiceAttachment();
                        att.ServiceID = serviceinfo.ServiceID;
                        att.ImagePath = path;
                        att.VideoPath = "";
                        att.VideoLength = "";
                        att.State = (int)Common.Enum.auvState.Enabled;
                        att.IsDel = (int)Common.Enum.auvDel.NotDel;

                        att.CreateDate = DateTime.Now;
                        att.UpdateDate = DateTime.Now;
                        att.BeginDate = DateTime.Now;
                        att.EndDate = DateTime.Now; ;
                        ServiceAttachmentBLL.Instance.Add(att);
                    }
                }
                daoManager.CommitTransaction();
            }
            catch
            {
                daoManager.RollBackTransaction();
                throw;
            }
        }
        #endregion

        #region 根据服务ID获取所有图片附件，不包括视频
        /// <summary>
        /// 根据服务ID获取所有图片附件，不包括视频
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public IList<ServiceAttachment> GetAttachWithoutVideo(string serviceID)
        {
            try
            {
                Hashtable ht = new Hashtable();
                ht.Add("ServiceID", serviceID);
                ht.Add("IsVideo", false);
                return ServiceAttachmentSqlMapDao.Instance.GetListByParameters(ht);
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region##修改服务信息
        /// <summary>
        /// 修改服务信息
        /// 创建人：Wilson
        /// 创建时间：2011-10-28
        /// </summary>
        /// <param name="serviceinfo"></param>
        public void UpdateServiceInfo(ServiceInfo serviceinfo)
        {
            try
            {
                dao.Update(serviceinfo);
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion

        #region  分页
        /// <summary>
        /// 分页（已弃用）
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="FieldList">返回字段，全部用*</param>
        /// <param name="PrimaryKey">主键</param>
        /// <param name="Where">where条件</param>
        /// <param name="Order">排序必须跟有asc或desc</param>
        /// <param name="SortType">排序规则 1:正序asc 2:倒序desc 3:多列排序方法</param>
        /// <param name="RecorderCount">记录总数 0:会返回总记录</param>
        /// <param name="PageSize">页面大小</param>
        /// <param name="PageIndex">当前页</param>
        /// <param name="TotalCount">记录总数 0:会返回总记录</param>
        /// <param name="TotalPageCount">返回总页数</param>
        /// <returns></returns>
        public System.Collections.Generic.IList<ServiceInfo> GetServiceInfoListPage(string TableName, string FieldList, string PrimaryKey, string Where, string Order, int SortType, int RecorderCount, int PageSize, int PageIndex, ref int TotalCount, ref int TotalPageCount)
        {
            try
            {
                Hashtable ht = new Hashtable();
                ht.Add("TableName", TableName);
                ht.Add("FieldList", FieldList);
                ht.Add("PrimaryKey", PrimaryKey);
                ht.Add("Where", Where);
                ht.Add("Order", Order);
                ht.Add("SortType", SortType);
                ht.Add("RecorderCount", RecorderCount);
                ht.Add("PageSize", PageSize);
                ht.Add("PageIndex", PageIndex);
                ht.Add("TotalCount", TotalCount);
                ht.Add("TotalPageCount", TotalPageCount);

                IList<ServiceInfo> list = dao.GetServiceInfoListPage(ht);

                TotalCount = (int)ht["TotalCount"];
                TotalPageCount = (int)ht["TotalPageCount"];
                return list;
            }
            catch
            {

                throw;
            }
        }



        public IList<ServiceInfo> GetServiceInfoListPage(NetPager pager)
        {
            try
            {
                return dao.GetServiceInfoListPage(pager);
            }
            catch
            {

                throw;
            }
        }

        #endregion

        #region 获取信息的所有关键字
        /// <summary>
        /// 获取信息的所有关键字
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public string GetTagList(string serviceID)
        {
            try
            {
                string taglist = "";
                IList<ServiceKeyRela> list = BLL.ServiceKeyRelaBLL.Instance.GetKeysByServiceID(null, serviceID);
                foreach (var sk in list)
                {
                    if (taglist == "")
                    {
                        taglist = sk.Keyword;
                    }
                    else
                    {
                        taglist += "," + sk.Keyword;
                    }
                }
                return taglist;
            }
            catch
            {
                throw;
            }
        }

        #endregion

        #region 修改服务信息的状态
        /// <summary>
        /// 修改服务信息的状态
        /// </summary>
        /// <param name="serviceID"></param>
        /// <param name="statusID"></param>
        public void ChangeStatus(string serviceID, int statusID)
        {
            try
            {
                ServiceInfo service = new ServiceInfo();
                service = GetDetail(serviceID);
                service.StatusID = statusID;
                dao.Update(service);
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region##通过用户ID和服务ID得到用户其它服务
        /// <summary>
        /// 通过用户ID和服务ID得到用户其它服务
        /// 创建人:Wilson
        /// 创建时间：2011-10-25
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="serviceId"></param>
        /// <returns></returns>
        public System.Collections.Generic.IList<ServiceInfo> GetUserServiceElseByUserId(string topCount, string userId, string serviceId)
        {
            try
            {
                Hashtable ht = new Hashtable();
                ht.Add("TopCounts", topCount);
                ht.Add("UserID", userId);
                ht.Add("ServiceID", serviceId);
                ht.Add("StatusID", Convert.ToInt32(AUV5.Common.Enum.ServiceStatus.Active));
                ht.Add("State", Convert.ToInt32(AUV5.Common.Enum.auvState.Enabled));
                ht.Add("IsDel", Convert.ToInt32(AUV5.Common.Enum.auvDel.NotDel));
                return dao.GetUserServiceElseByUserId(ht);
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region##通过用户ID得到用户服务
        /// <summary>
        /// 通过用户ID得到用户服务
        /// 创建人：Wilson
        /// 创建时间：2011-10-26
        /// </summary>
        /// <param name="objParameters"></param>
        /// <returns></returns>
        public IList<ServiceInfo> GetServiceListByUserId(string userId, int statusId)
        {
            try
            {
                Hashtable ht = new Hashtable();
                ht.Add("UserID", userId);
                ht.Add("StatusID", statusId);
                ht.Add("State", Convert.ToInt32(AUV5.Common.Enum.auvState.Enabled));
                ht.Add("IsDel", Convert.ToInt32(AUV5.Common.Enum.auvDel.NotDel));
                return dao.GetServiceListByUserId(ht);
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region##通过用户ID得到用户总分
        /// <summary>
        /// 通过用户ID得到用户总分
        /// 创建人：Wilson
        /// 创建时间:2011-11-23
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int GetUserScoreByUserId(string userId)
        {
            try
            {

                int goodRateScore = dao.GetGoodRateSumByUserId(userId) * new AUV5.BLL.AuvLevelBLL().GoodRateScore;   //好评分数
                int badRateScore = dao.GetBadRateSumByUserId(userId) * new AUV5.BLL.AuvLevelBLL().BadRateScore;      //差评分数
                int forceScore = AUV5.BLL.OrderInfoBLL.Instance.GetForceClosedOrderInfoCountBySeller(userId) * new AUV5.BLL.AuvLevelBLL().ForceScore;  //强制取消分数

                return goodRateScore + badRateScore + forceScore;
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region##通过用户ID得到好评的总数
        /// <summary>
        /// 通过用户ID得到好评的总数
        /// 创建人：Wilson
        /// 创建时间：2011-10-26
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int GetGoodRateSumByUserId(string userId)
        {
            try
            {
                return dao.GetGoodRateSumByUserId(userId);
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region##通过用户ID得到差评的总数
        /// <summary>
        /// 通过用户ID得到差评的总数
        /// 创建人：Wilson
        /// 创建时间：2011-10-26
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int GetBadRateSumByUserId(string userId)
        {
            try
            {
                return dao.GetBadRateSumByUserId(userId);
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region##得到好评差评总数
        /// <summary>
        /// 得到好评差评总数
        /// 创建人：Wilson
        /// 创建时间：2011-10-26
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int GetRateSumByUserId(string userId)
        {
            return GetGoodRateSumByUserId(userId) + GetBadRateSumByUserId(userId);
        }
        #endregion

        #region 根据收藏列表，获得信息列表
        /// <summary>
        /// 根据收藏列表，获得信息列表
        /// </summary>
        /// <param name="list"></param>
        public IList<ServiceInfo> GetServiceByFavoriteList(IList<Favorite> list)
        {
            try
            {
                if (list.Count != 0)
                {
                    Hashtable ht = new Hashtable();
                    ht.Add("List", list);
                    return dao.GetListByParameters(ht);
                }
                else
                {
                    return null;
                }
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region 根据各种参数查询显示首页的服务信息
        /// <summary>
        /// 根据各种参数查询显示首页的服务信息
        /// </summary>
        /// <param name="category">服务类别(ID或enName),可以为空</param>
        /// <param name="order">排序类别(Random,Newest,Popularity,Hotsale,Rating)</param>
        /// <param name="username">用户名（可以为空）</param>
        /// <param name="hasvideo">是否有视频（0：全部1：有2：没有）</param>
        /// <param name="mode">显示模式（1：Show,2:Manage,3:All）</param>
        /// <param name="pageindex">当前页，不能为空</param>
        /// <param name="pagesize">每页显示记录数，不能为空</param>
        /// <param name="recordcount">记录总数，不能为空</param>
        /// <returns></returns>
        public IList<ServiceInfo> GetPagedServiceInfo(string category, string key, string order, string username, int hasvideo, int mode, int pageindex, int pagesize, ref int recordcount)
        {
            try
            {
                string sqlwhere = QueryParameter(category, username, hasvideo, mode);
                string orderby = "CreateDate desc,StatusID desc,ServiceID desc";
                if (!string.IsNullOrEmpty(order))
                {
                    switch (order)
                    {
                        case "Random": orderby = "newid(),StatusID desc,CreateDate desc,ServiceID desc"; break;
                        case "Newest": orderby = "CreateDate desc,StatusID desc,ServiceID desc"; break;
                        case "Popularity": orderby = "ViewCount desc,StatusID desc,CreateDate desc,ServiceID desc"; break;
                        case "Rating": orderby = "GoodRating desc,StatusID desc,CreateDate desc,ServiceID desc"; break;
                        case "Hotsale": orderby = "SalesCount desc,StatusID desc,CreateDate desc,ServiceID desc"; break;
                        default: break;
                    }
                }
                Model.NetPager pager = new Model.NetPager();

                //关键字
                if (!string.IsNullOrEmpty(key))
                {
                    Model.Keyword result = BLL.KeywordBLL.Instance.GetDetailByContent(key);
                    if (result != null)
                    {
                        pager.TableName = "(select a.* from ServiceInfo a right join ServiceKeyRela b on a.ServiceID=b.ServiceID inner join Keyword c on b.KeyID=c.KeyID where Content='" +
                            result.Content + "') as Temp";
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    pager.TableName = "ServiceInfo";
                }
                pager.PageIndex = pageindex;
                pager.PrimaryKey = "ServiceID";
                pager.Where = sqlwhere;
                pager.Order = orderby;
                pager.SortType = (int)Common.Enum.SortType.Multi;
                pager.PageSize = pagesize;



                IList<Model.ServiceInfo> list = GetServiceInfoListPage(pager);
                recordcount = pager.TotalCount;
                return list;
            }
            catch
            {

                throw;
            }
        }

        ///根据传入的参数初始化NetPager对象,如果有非法参数，则返回Null
        private string QueryParameter(string category, string username, int hasvideo, int mode)
        {
            try
            {
                string sqlwhere = "";
                //显示模式
                switch (mode)
                {
                    case 1: sqlwhere = "StatusID>=" + ((int)Common.Enum.ServiceStatus.Active).ToString() + " and State=1 and IsDel=0"; break;
                    case 2: sqlwhere = "State=1 and IsDel=0"; break;
                    case 3: sqlwhere = "1=1"; break;
                    default:
                        sqlwhere = "1!=1";
                        return sqlwhere;
                }
                //服务类别
                if (!string.IsNullOrEmpty(category))
                {
                    //判断参数是否有效,同时防止通过修改参数进行SQL注入
                    //将参数由CategoryID改为categoryName时，只要修改此处即可
                    Model.ServiceCategory servicecategory = BLL.ServiceCategoryBLL.Instance.GetCategoryByIDOrCode(category);
                    if (servicecategory != null)
                    {
                        sqlwhere += " and CategoryID='" + servicecategory.CategoryID + "'";
                    }
                    else
                    {
                        sqlwhere += " and 1!=1";
                        return sqlwhere;
                    }
                }

                //用户
                if (!string.IsNullOrEmpty(username))
                {
                    //判断用户名是否有效,防止通过修改参数进行SQL注入
                    Model.UserInfo user = BLL.UserInfoBLL.Instance.GetDetailByName(username);
                    if (user != null)
                    {
                        sqlwhere += " and UserID='" + user.UserID + "'";
                    }
                    else
                    {
                        sqlwhere += " and 1!=1";
                        return sqlwhere;
                    }

                }
                //是否有视频
                switch (hasvideo)
                {
                    case 0: break;
                    case 1: sqlwhere += " and HasVideo=1"; break;
                    case 2: sqlwhere += " and HasVideo=0"; break;
                    default:
                        sqlwhere += " and 1!=1";
                        return sqlwhere;
                }
                return sqlwhere;
            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region    附件处理相关  add by  Vinlon    2011-11-05


        /// <summary>
        /// 图片处理 预览图按比例处理（450*450）  显示图（450*450），生成缩略图（75*75）,并删除临时文件 
        /// </summary>
        /// <param name="imgpath"></param>
        /// <returns></returns>
        public string ImageProcess(string imgpath)
        {
            int minheight = Common.CommonDefine.SERVICE_IMAGE_HEIGHT;
            int minwidth = Common.CommonDefine.SERVICE_IMAGE_WIDTH;
            int thumbheight = Common.CommonDefine.SERVICE_THUMB_HEIGHT;
            int thumbwidth = Common.CommonDefine.SERVICE_THUMB_WIDTH;
            try
            {
                ///原图   UploadFile/Temp/Image/2011/10/26/201110260530168582.jpg
                ///预览图 UploadFile/Image/2011/10/26/201110260530168582_preview.jpg
                ///缩略图 UploadFile/Image/2011/10/26/201110260530168582_thumb.jpg
                ///显示图 UploadFile/Image/2011/10/26/201110260530168582.jpg 
                if (File.Exists(HttpContext.Current.Server.MapPath(imgpath)))
                {
                    //图片永远保存为jpg格式
                    string showimg = Path.ChangeExtension(imgpath.Replace("/Temp/", "/"), ".jpg");
                    string previewimg = GetImagePreview(showimg);
                    string thumbimg = GetImageThumb(showimg);


                    //图片转化。显示图及预览图
                    Common.ImageProcess.ImageToProperSize(imgpath, minwidth, minheight, showimg, previewimg);

                    //缩略图
                    Common.ImageProcess.ImageToProperSize(imgpath, thumbwidth, thumbheight, thumbimg, null);

                    //if (!Directory.Exists(HttpContext.Current.Server.MapPath(Path.GetDirectoryName(showimg))))
                    //{
                    //    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(Path.GetDirectoryName(showimg)));
                    //}
                    ////由上传图生成预览图
                    //Common.FileHelper.MakeScaleMap(imgfile, minheight, minwidth, HttpContext.Current.Server.MapPath(previewimg));
                    ////由预览图生成显示图
                    //Common.FileHelper.CutImage(HttpContext.Current.Server.MapPath(previewimg), minheight, minwidth, HttpContext.Current.Server.MapPath(showimg));
                    ////由显示图生成缩略图
                    //Common.FileHelper.MakeThumbNail(HttpContext.Current.Server.MapPath(showimg), HttpContext.Current.Server.MapPath(thumbimg), thumbwidth, thumbheight);
                    //File.Delete(HttpContext.Current.Server.MapPath(imgpath));
                    return showimg;
                }
                else
                {
                    return "";
                }
            }
            catch
            {
                throw;
            }
        }



        #endregion

        #region 删除服务
        /// <summary>
        /// 删除服务（将IsDel设为1）
        /// 如果有未完成订单，则不可以删除
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        public string DeleteService(ServiceInfo service)
        {
            try
            {


                int queue = OrderItemBLL.Instance.GetOrderItemQuantityCountByCondition(service.ServiceID, (int)Common.Enum.OrderState.Payment);
                if (queue > 0)
                {
                    return "有" + queue.ToString() + "个订单在队列中，不可删除";
                }
                else
                {
                    service.IsDel = 1;
                    Update(service);

                    IList<AUV5.Model.OrderInfo> defaultList = AUV5.BLL.OrderInfoBLL.Instance.GetOrderInfoByServiceIdAndStatusId(service.ServiceID, Convert.ToInt32(AUV5.Common.Enum.OrderState.Default));

                    foreach (AUV5.Model.OrderInfo orderInfo in defaultList)
                    {
                        orderInfo.StatusID = Convert.ToInt32(AUV5.Common.Enum.OrderState.Cloesd);

                        AUV5.BLL.OrderInfoBLL.Instance.Update(orderInfo);

                        AUV5.BLL.BulletinBLL.Instance.AddBulletin("订单提示", "此服务已关闭", orderInfo.Buyer, false, Convert.ToInt32(AUV5.Common.Enum.bulletinStatus.BeBuyer), orderInfo.OrderID);
                    }

                    return "100";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
                throw;
            }
        }
        #endregion

        #region  根据标题的模糊匹配获取服务信息

        /// <summary>
        /// 根据标题的模糊匹配获取服务信息
        /// </summary>
        /// <param name="title"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public IList<ServiceInfo> GetListWhereTitleLike(string title, int count)
        {
            try
            {
                if (!string.IsNullOrEmpty(title) && count > 0)
                {
                    Hashtable ht = new Hashtable();
                    ht.Add("title", "%" + title + "%");//模糊查询 
                    ht.Add("topCount", count);
                    ht.Add("statusID", (int)Common.Enum.ServiceStatus.Active);
                    ht.Add("state", (int)Common.Enum.auvState.Enabled);
                    ht.Add("isDel", (int)Common.Enum.auvDel.NotDel);
                    return dao.GetListByTitleOrDesc(ht);
                }
                else
                {
                    return null;
                }
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region 根据描述的模糊匹配获取服务信息
        /// <summary>
        /// 根据描述的模糊匹配获取服务信息
        /// </summary>
        /// <param name="query"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public IList<ServiceInfo> GetListWhereDescLike(string description, int count)
        {
            try
            {
                if (!string.IsNullOrEmpty(description) && count > 0)
                {
                    Hashtable ht = new Hashtable();
                    ht.Add("description", "%" + description + "%");//模糊查询 
                    ht.Add("topCount", count);
                    ht.Add("statusID", (int)Common.Enum.ServiceStatus.Active);
                    ht.Add("state", (int)Common.Enum.auvState.Enabled);
                    ht.Add("isDel", (int)Common.Enum.auvDel.NotDel);
                    return dao.GetListByTitleOrDesc(ht);
                }
                else
                {
                    return null;
                }
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region  判断标题是否已存在
        /// <summary>
        /// 判断标题是否已存在
        /// </summary>
        /// <param name="title"></param>
        /// <param name="serviceid"></param>
        /// <returns></returns>
        public bool TitleExists(string title, string serviceid)
        {
            try
            {
                ServiceInfo service = GetDetailByTitle(title);
                if (string.IsNullOrEmpty(serviceid))
                {
                    return service != null;
                }
                else
                {
                    return service != null && service.ServiceID != serviceid;
                }

            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region 对过长的标题，截取其中一部分
        /// <summary>
        /// 对过长的标题，截取其中一部分
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public object SubTitle(string title, int length)
        {
            if (title.Length > length)
            {
                return title.Substring(0, length) + "...";
            }
            else
            {
                return title;
            }
        }
        #endregion

    }
}
